public class FourSort {
    public void straightInsertion(int[] array) {
        int len = array.length;
        for(int i = 1; i < len ; i++) {
            int count = array[i];
            int j = i - 1;
            for( ; j >= 0; j --) {
                if(count < array[j]) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
            }
            array[j + 1] = count;
        }
    }
    public void straightInsertion(int[] array,int gap) {
        int len = array.length;
        for(int i = gap; i < len ; i++) {
            int count = array[i];
            int j = i - gap;
            for( ; j >= 0; j-=gap) {
                if(count < array[j]) {
                    array[j + gap] = array[j];
                } else {
                    break;
                }
            }
            array[j + gap] = count;
        }
    }
    public void shellSort(int[] arrary) {
        int gap = arrary.length;
        while(gap  > 0) {
            gap = gap /2;
            straightInsertion(arrary,gap);
        }
    }
    public  void selectSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            int j = i+1;
            for (; j < array.length; j++) {
                if(array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            swap(array,i,minIndex);
        }
    }

    private  void swap(int[] array,int i,int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
    public  void heapSort(int[] array) {
        createBigHeap(array);
        int end = array.length-1;
        while (end > 0) {
            swap(array,0,end);
            shiftDown(array,0,end);
            end--;
        }
    }

    private  void createBigHeap(int[] array) {
        for (int parent = (array.length-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(array,parent,array.length);
        }
    }

    private  void shiftDown(int[] array,int parent,int len) {
        int child = 2*parent+1;
        while (child < len) {
            if(child+1 < len && array[child] < array[child+1]) {
                child++;
            }
            if(array[child] > array[parent]) {
                swap(array,child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }

}
